package com.seasugar.raggie.utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class QiniuUtil {

    public static final String url = "rbjvd01tv.bkt.clouddn.com";

    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.accessSecretKey}")
    private String accessSecretKey;

    public boolean upload(MultipartFile file, String fileName) {

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huadongZheJiang2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String bucket = "seasugar";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(uploadBytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

//    public boolean download(String filename) {
//        // domain   下载 domain, eg: qiniu.com【必须】
//        // useHttps 是否使用 https【必须】
//        // key      下载资源在七牛云存储的 key【必须】
//        try {
//            DownloadUrl url = new DownloadUrl("rbjvd01tv.bkt.clouddn.com", true, filename);
////        url.setAttname(attname) // 配置 attname
////                .setFop(fop) // 配置 fop
////                .setStyle(style, styleSeparator, styleParam); // 配置 style
//            // 带有效期
//            long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
//            Auth auth = Auth.create(accessKey, accessSecretKey);
//            String urlString = url.buildURL(auth, expireInSeconds);
//            System.out.println(urlString);
//            return true;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//        return false;
//    }
}

